package cn.com.libertymutual.core.util;

/**
 * <pre>实用工具包</pre>
 * @author wyl
 * @version 1.0
 * @jdk 1.6
 * @date 2013-01-20
 * @company 信诚人寿
 * @mofidy
 * @reivew 
 */
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;


import sun.misc.BASE64Decoder;

public class UtilTool {
	/**
	 * 计算年龄
	 * @param beginDate 开始日期
	 * @param endDate 结束日期
	 * @param formart 日期格式
	 * @return String 年龄
	 * @throws Exception
	 */
	public static int doCalculateDatePoor(String beginDate,String endDate,String formart)throws Exception{
		SimpleDateFormat myFormatter = new SimpleDateFormat(formart);
		Calendar cal = Calendar.getInstance();
		Date beDate= myFormatter.parse(beginDate);
		Date edDate = myFormatter.parse(endDate);
		if(edDate.getTime()<beDate.getTime()){
//			logger.debug("当前系统日期为["+endDate+"]，出生日期为["+beginDate+"]不符合要求！");
			throw new Exception("年龄计算异常！");
		}
		//当前日期
		cal.setTime(edDate);
		int yearNow = cal.get(Calendar.YEAR);//年
		int monthNow = cal.get(Calendar.MONTH)+1;//月
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);//日
		//出生日期
		cal.setTime(beDate);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH)+1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
		int age = yearNow - yearBirth;
		if(age>0){
			if(monthNow < monthBirth){
				age--;
			}else if(monthNow == monthBirth){
				if(dayOfMonthNow<dayOfMonthBirth){
					age--;
				}
			}
		}
		return age;
	}
	/**
	 * 字符串日期格式的转换
	 * 
	 * @param date 当前字符串日期
	 * @param formatOne 当前日期格式
	 * @param formatTwo 转换日期格式
	 * @return String
	 * @throws Exception
	 */
	public static String getTimeFormat(String date ,String formatOne,String formatTwo)throws Exception{
		String str;
		try {
			Date dt = new SimpleDateFormat(formatOne).parse(date);
			str = new SimpleDateFormat(formatTwo).format(dt);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return str ;
	}
	/**
	 * 比较日期大小
	 * 结束日期是否大于开始日期
	 * @param beginDate 开始日期
	 * @param endDate 结束日期
	 * @param formart 比较的日期格式
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean dateCompare(String beginDate,String endDate,String formart)throws Exception{
		SimpleDateFormat myFormatter = new SimpleDateFormat(formart);
		Date beDate= myFormatter.parse(beginDate);
		Date edDate= myFormatter.parse(endDate);
		if(edDate.getTime() >= beDate.getTime()){
			return true ;
		}
		return false ;
	}
	/**
	 * 得到当前系统日期
	 * @param format 日期格式
	 * @return String 字符串
	 */
	public static String getCurrentSysDate(String format) {
		return new SimpleDateFormat(format).format(new Date());
	}
	/**
	 * 获得客户端真实IP
	 * @param request  
	 * @return
	 */
	public static String getRemortIP(HttpServletRequest request) { 
	    if (request.getHeader("x-forwarded-for") == null) { 
	        return request.getRemoteAddr(); 
	    } 
	    return request.getHeader("x-forwarded-for"); 
	}
	
	/**
	 * <pre>将时间格式 字符串转换为数据库时间对象</pre>
	 * <pre>格式:yyyy-MM-dd;如2013-01-31</pre>
	 * @param java.sql.date 
	 * @return
	 * @throws ParseException
	 */
	public static java.sql.Date str2Date(String date) throws ParseException{
		if(date==null || date.equals("")) return null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		long t = sdf.parse(date).getTime();
		return new java.sql.Date(t);
	}
	/**
	 * <pre>将时间格式 字符串转换为数据库时间对象</pre>
	 * <pre>格式:yyyyMMdd;如20130131</pre>
	 * @param date 
	 * @return
	 * @throws ParseException
	 */
	public static java.sql.Date convert2Date(String date) throws ParseException{
		if(date==null || date.equals("")) return null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		long t = sdf.parse(date).getTime();
		return new java.sql.Date(t);
	}
	/**
	 * <pre>获得当前时间的数据库时间对象</pre>
	 * 
	 * @return java.sql.Timestamp
	 */
	public static Timestamp getCurrentTime(){
		return new java.sql.Timestamp(new java.util.Date().getTime());
	}
	/**
	 * 获得当前日期
	 * @return  java.sql.Date
	 */
	public static java.sql.Date getCurrentDate(){
		return new java.sql.Date(new java.util.Date().getTime());
	}
	
	/**
	 * 格式化为yyyy-MM-dd串
	 * @param d
	 * @return
	 */
	public static String format(java.sql.Date d){
		if(d == null) return "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		return sdf.format(d.getTime());
	}
	public static String format(java.sql.Timestamp d){
		if(d == null) return "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		return sdf.format(d.getTime());
	}
	
	/**
	 * 获取当前时间戳，精确到毫秒
	 * @return
	 */
	public static String getCurrentTimestamp(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
		return sdf.format(date.getTime());
	}
	
	/**
	 * 转换为yyymmdd格式日期串
	 * @param date
	 * @return
	 */
	public static String dateCovert(java.sql.Date date){
		if(date == null) return "";
		return new SimpleDateFormat("yyyyMMdd").format(date);
	}
	
	public static String distillAge(java.sql.Date date){
		if(date == null) return "";
		int y =date.getYear()+1900;
		int m = date.getMonth();
		int d = date.getDate();
		Calendar c = Calendar.getInstance();
		int cy = c.get(Calendar.YEAR);
		int cd = c.get(Calendar.DAY_OF_MONTH);
		int cm = c.get(Calendar.MONTH);
		if(cd - d  > 0) m--;
		if(cm - m > 0) y--;
		int age = cy - y;
		return age+"";
	}
	
	/**
	 * 根据日期格式时间串，计算年龄
	 * @param ageStr
	 * @return
	 * @throws ParseException
	 */
	public static int calAge(String ageStr) throws ParseException{
		if(ageStr == null) return 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		java.util.Date date = sdf.parse(ageStr);
		
		int y =date.getYear()+1900;
		int m = date.getMonth();
		int d = date.getDate();
		Calendar c = Calendar.getInstance();
		int cy = c.get(Calendar.YEAR);
		int cd = c.get(Calendar.DAY_OF_MONTH);
		int cm = c.get(Calendar.MONTH);
		if(cd - d  > 0) m--;
		if(cm - m > 0) y--;
		int age = cy - y;
		return age;
	}
	/**
	 * 生成 验证码
	 * @return
	 */
	public static String makeCheckCode(){
		String sRand = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {    
	        String rand = String.valueOf(random.nextInt(10));
	        sRand += rand;
		}
		return sRand;
	}
	
	/**
	 * 为数字每隔三位加上逗号
	 */
	public static String addComma(double value){
		 DecimalFormat df = null; 
		 df = new DecimalFormat("###,###,###.00");  
		 String str = df.format(value);
		 return str;
	}
	
	public static void main(String []arg){
		
		System.out.println(UtilTool.makeCheckCode());
	}
	
    /*********************************************************************
     * 半角转全角 half  whole
     * @return
     ********************************************************************/
     public static final String changeHalfToWhole(String half) {
    	 if (half==null){
    		 return half;
    	 }
         char[] c = half.toCharArray();
         for (int i = 0; i < c.length; i++) {
             if (c[i] == 32) {
                 c[i] = (char) 12288;
                 continue;
             }
             if (c[i] < 127){
                 c[i] = (char) (c[i] + 65248);
             }
         }
         return new String(c);
     }

     /*********************************************************************
      * 全角转半角
      * @return
      ********************************************************************/
     public static final String changeWholeToHalf(String whole) {
    	 char[] c = whole.toCharArray();
         for (int i = 0; i < c.length; i++) {
             if (c[i] == 12288) {
                 c[i] = (char) 32;
                 continue;
             }
             if (c[i] > 65280 && c[i] < 65375){
            	 c[i] = (char) (c[i] - 65248);
             }
         }
         return new String(c);
     }
     
     /*********************************************************************
      * 判断字符串是否时数字类型
      * @return
      ********************************************************************/
 	public static boolean isDigital(String number){
 		try {
 			Double.parseDouble(number);
 			return true;
 		} catch (Exception e) {
 			return false;
 		}
 	}
 	/**
 	 * 规则引擎发送数据
 	 * @param xmlData
 	 * @param reqUrl
 	 * @return
 	 * @throws Exception
 	 *  zhangw 2013-12-30
 	 */
 	public String sendData(String xmlData, String reqUrl) throws Exception {
 		//URL;
 		String SERVER_URL = reqUrl;
 		// 开启连接
 		URL uploadServlet = new URL(SERVER_URL);
 		URLConnection servletConnection = uploadServlet.openConnection();
 		// System.out.println("请求系统连接成功,URL:" + servletConnection.getURL());
 		// 如果为 true，则只要有条件就允许协议使用缓存。
 		servletConnection.setUseCaches(false);
 		// URL 连接可用于输入和/或输出。将 doOutput 标志设置为 true，指示应用程序要将数据写入 URL 连接。
 		servletConnection.setDoOutput(true);
 		// URL 连接可用于输入和/或输出。将 doInput 标志设置为 true，指示应用程序要从 URL 连接读取数据。
 		servletConnection.setDoInput(true);
 		// 开启流，写入XML数据
 		BufferedOutputStream output = new BufferedOutputStream(servletConnection.getOutputStream());
 		output.write(xmlData.getBytes("GBK"));// UTF-8
 		output.close();//必须在此关闭流
 		DataInputStream input = null;
 		ByteArrayOutputStream byteOut = null;
 		try {
 			input = new DataInputStream(servletConnection.getInputStream());
 			byteOut = new ByteArrayOutputStream();
 			byte[] data = null;
 			byte[] b = new byte[2048];
 			int read = 0;
 			while ((read = input.read(b)) > 0) {
 				byteOut.write(b, 0, read);
 			}
 			data = byteOut.toByteArray();
 			String dataString = new String(data);
 			System.out.println("规则引擎返回数据:\n" + dataString);
 			input.close();
 			return dataString;
 		} catch (Exception e) {
 			e.printStackTrace();
 			throw e;
 		}finally{
 			if(null != output)output.close();
 			if(null != byteOut)byteOut.close();
 			if(null != input)input.close();
 		}
 	}
 	/**
 	 * 扫描文件目录的所有文件
 	 * @param filePath 文件夹或文件全路径
 	 * @throws Exception
 	 */
 	public static void doFilePath(String filePath)throws Exception{
 		File[] file = new File(filePath).listFiles();
 		if ( file != null ) {
			for (int i = 0; i < file.length; i++) {
				if(file[i].isDirectory()){
					doFilePath(file[i].getAbsolutePath());
				}else if(file[i].isFile()){
					file[i].getAbsolutePath();
				}
			}
 		}
 	}
 	/**
 	 * 删除目录（文件夹、文件）
 	 * @author xrxianga
 	 * @param sPath 被删除目录的文件路径
 	 * @date 2014-9-9下午05:55:42
 	 */
    public static void deleteDirectory(String sPath) {
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        if (dirFile.exists() || dirFile.isDirectory()) {
        	File[] files = dirFile.listFiles();
	        if ( files != null ) {
	            for (File filePath : files) {
	            	if(filePath.isFile()) {
	            		File file = new File(filePath.getAbsolutePath());  
	                    if (file.isFile() && file.exists()) {  
	                        file.delete();  
	                    }
	                }else {
	                    deleteDirectory(filePath.getAbsolutePath());
	                }
	            }
        	}
            dirFile.delete();
        }
    }
    /**
     * 删除指定目录下的所有文件
     * @author xrxianga
     * @param path
     * @date 2014-9-10下午03:38:24
     */
    public static void deleteDirectoryFile(String path) {
    	if (!path.endsWith(File.separator)) {
    		path = path + File.separator;
        }
        File dirFile = new File(path);
        if (dirFile.exists() || dirFile.isDirectory()) {
        	File[] files = dirFile.listFiles();
        	if ( files != null ) {
	            for (File filePath : files) {
	            	if(filePath.exists() && filePath.isFile()) {
	            		File file = new File(filePath.getAbsolutePath());  
	                    if (file.isFile() && file.exists()) {
	                        file.delete();
	                    }
	                }
	            }
        	}
        }
    }
    /**
     * 删除文件
     * @author xrxianga
     * @param sPath 文件全路径
     * @date 2014-9-9下午06:00:43
     */
    public static void deleteFile(String sPath) {
        File file = new File(sPath);
        if (file.isFile() && file.exists()) {
            file.delete();
        }
    }
    /**
     * 
     * @author xrxianga
     * @param f 被压缩文件夹或文件
     * @param out 压缩包
     * @param dir
     * @throws IOException
     * @date 2014-9-9下午06:44:14
     */
    public static void put(File f, ZipOutputStream out, String dir) throws IOException {
    	int BUFFER = 2048;
		if (f.exists() && f.isDirectory()) { 
			File[] files = f.listFiles();  
			if ( files != null && files.length > 0 ) {
				dir = dir + (dir.length() == 0? "" : "/") + f.getName();
				for (File file : files) { 
					put(file, out, dir); 
				}
			}
		} else if(f.exists() && f.isFile()){ 
			byte[] data = new byte[BUFFER]; 
			FileInputStream fi = new FileInputStream(f); 
			BufferedInputStream origin = new BufferedInputStream(fi, BUFFER); 
			dir = dir.length() == 0 ?"" : dir + "/" + f.getName(); 
			ZipEntry entry = new ZipEntry(dir); 
			out.putNextEntry(entry); 
			int count; 
			while ((count = origin.read(data, 0, BUFFER)) != -1) { 
				out.write(data, 0, count); 
			} 
			origin.close();
			fi.close();
		} 
    }
    /**
     * 获取随机数
     * @author xrxianga
     * @param num 随机位数
     * @return
     * @throws Exception
     * @date 2014-9-9下午07:51:04
     */
    public static String doRandom()throws Exception{
    	String msgcontant = "";
    	for(int i=0;i<10;i++){
			double b =Math.random()*1000000000+100000000;
			String number = String.valueOf(Math.floor(b));
			msgcontant = number.substring(0, 6);
		}
    	return msgcontant.replace(".", "9");//防止有逗号存在
    }
    /**
	 * 图片存盘
	 * @author xrxianga
	 * @param imgData 图片码
	 * @throws Exception
	 * @date 2014-10-13下午04:30:21
	 */
	public static void doPhoto(String imgData,String filePath)throws Exception{
		BASE64Decoder base64 = new BASE64Decoder();
		byte []bytes = base64.decodeBuffer(imgData);
		for(int j=0;j<bytes.length;j++){
			if(bytes[j]<0){
				bytes[j]+=256;
			}
		}
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		String path = "";
		for (int i = 0; i < 10000; i++) {
			String num = UtilTool.doRandom();//随机数
			file = new File((filePath + File.separator + num+".jpg").toString());
			if(!file.exists()){
				path = file.getPath().toString();
				break;
			}
		}
		FileOutputStream out = new FileOutputStream(path);					
		out.write(bytes);
		out.flush();
		out.close();
	}
}
